package com.glsc.ngateway.platform.service.itflow.flowstrategy;

import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.util.CollectionUtils;
import com.glsc.ngateway.common.api.shortmsg.bo.MessageGenericVo;
import com.glsc.ngateway.common.api.shortmsg.feign.IFeignShortmsgService;
import com.glsc.ngateway.common.api.common.enums.Constant;
import com.glsc.ngateway.common.api.common.enums.PlatformConstant;
import com.glsc.ngateway.common.base.domain.mysql.gateway.other.SystemConfig;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.User;
import com.glsc.ngateway.common.api.flowable.dto.param.ParamCopyDto;
import com.glsc.ngateway.common.api.flowable.dto.task.doTaskParam.system.SystemRejectParamDto;
import com.glsc.ngateway.common.api.flowable.resp.FlowableResponse;
import com.glsc.ngateway.common.api.flowable.resp.ResponseSituationDto;
import com.glsc.ngateway.platform.service.MailService;
import com.glsc.ngateway.platform.service.SystemConfigService;
import com.glsc.ngateway.platform.service.UserService;
import com.glsc.ngateway.common.api.flowable.feign.IFeignFlowableService;
import com.glsc.ngateway.platform.utils.JsonTool;
import org.apache.logging.log4j.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import javax.annotation.Resource;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author xuchang
 */
public class AbstractHandlerHelper {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Resource
    private IFeignFlowableService feignFlowableService;
    @Resource
    private MailService mailService;
    @Resource
    private UserService userService;
    @Resource
    private IFeignFlowableService flowableService;
    @Resource
    private IFeignShortmsgService iFeignShortmsgService;
    @Resource
    private SystemConfigService systemConfigService;
    @Value("${wechat.url}")
    private String weChatUrl;

    //流程待办列表页面
    public static final String GATEWAY_FLOW_TODO_URL = "http://zy.glsc.com.cn/gateway/workflowMgr/taskTodoQuery";

    //it流程
    public static final String GATEWAY_IT_FLOW_URL = "http://zy.glsc.com.cn/gateway/ITSystemList/";

    //事件流程
    public static final String GATEWAY_EVENT_URL = "http://zy.glsc.com.cn/gateway/accidentMgr/";

    //CMDB相关流程
    public static final String GATEWAY_CMDB_FLOW_URL = "http://zy.glsc.com.cn/gateway/CMDB/";

    public void copyPorcess(@NotBlank String processId, @NotBlank String operator, List<String> accountList, @NotBlank String mailTitle, @NotBlank String titleLink, @NotBlank String mailContent) {
        copyPorcess(processId, false, null, operator, accountList, mailTitle, titleLink, mailContent);
    }

    public void copyPorcess(@NotBlank String processId, boolean addComment, String taskId, @NotBlank String operator, List<String> accountList, @NotBlank String mailTitle, @NotBlank String titleLink, @NotBlank String mailContent) {
        if (CollectionUtils.isEmpty(accountList)) {
            logger.error("流程抄送-不存在抄送人");
            return;
        }
        List<User> userList = userService.findAllByAccountList(accountList);
        if (CollectionUtils.isEmpty(userList)) {
            logger.error("流程抄送-不存在抄送人");
            return;
        }
        String[] mails = userList.stream().map(User::getEmail).filter(StrUtil::isNotBlank).distinct().toArray(String[]::new);
        mailService.sendMail(mails, null, mailTitle, titleLink, mailTitle, mailContent, null, Constant.MAIL_TYPE_IT_FLOW);
        ParamCopyDto copyParam = new ParamCopyDto();
        copyParam.setProcessId(processId);
        copyParam.setAddComment(addComment);
        copyParam.setTaskId(taskId);
        copyParam.setSysid(PlatformConstant.SYS_ID_GATEWAY);
        copyParam.setUsernameSource(operator);
        copyParam.setUsernameDestination(String.join(",", accountList));
        //copyParam.setRemark(null);
        logger.info("流程-抄送:入参paramStopDto：" + JsonTool.objectToJson(copyParam));
        feignFlowableService.copyProcess(copyParam);
    }

    public void rejectSendMsg(@NotNull SystemRejectParamDto param, @NotNull String operator, @NotBlank String flowTitleFormat) {
        SystemConfig agentIdConfig = systemConfigService.findByCode("WECHAT_GATEWAY_APP_AGENTID");
        if (Objects.isNull(agentIdConfig) || Strings.isBlank(agentIdConfig.getConfigValue())) {
            logger.error("系统名称申请流程驳回后置处理异常：缺少配置WECHAT_GATEWAY_APP_AGENTID");
        } else {
            FlowableResponse<ResponseSituationDto> flowResp = flowableService.getProcessInfo(param.getProcessId());
            if (Objects.isNull(flowResp) || Objects.isNull(flowResp.getData())) {
                logger.error("系统名称申请流程驳回后置处理异常:未找到流程信息pid:{}", param.getProcessId());
            } else {
                ResponseSituationDto flow = flowResp.getData();
                iFeignShortmsgService.sendAgentMessageGeneric(
                        flow.getCurrentTaskInfoDtoList().stream()
                                .map(curTask -> {
                                    List<MessageGenericVo> list = new ArrayList<>();
                                    try {
                                        for (int i = 0; i < curTask.getCurrentAssigneeList().size(); i++) {
                                            list.add(
                                                    MessageGenericVo.builder()
                                                            .oaUserAccounts(List.of(curTask.getCurrentAssigneeList().get(i)))
                                                            .agentId(agentIdConfig.getConfigValue())
                                                            .textContent("【国联技术服务平台提醒】您有流程被驳回" +
                                                                    "<br><a href='" + weChatUrl + "'>" +
                                                                    String.format(flowTitleFormat, flow.getProcessTitle()) + "</a>")
                                                            .build()
                                            );
                                        }
                                    } catch (IndexOutOfBoundsException e) {
                                        logger.error("系统名称申请流程企微通知失败", e);
                                    }
                                    return list;

                                })
                                .flatMap(Collection::stream)
                                .collect(Collectors.toList())
                );
            }
        }
    }
}
